package com.auto.learning;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Dialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.auto.learning.activity.BookListActivity;
import com.auto.learning.activity.MyMessageActivity;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.activity.WebActivity;
import com.auto.learning.adapter.TabViewPagerAdapter;
import com.auto.learning.bean.BannerItem;
import com.auto.learning.bean.Banner_H5;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.BookListModel;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.bean.VersionInfo;
import com.auto.learning.event.BindSuccessEvent;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.event.MainShowTipEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.fragment.ChooseBookPageFragment;
import com.auto.learning.fragment.CollectPageFragment;
import com.auto.learning.fragment.HomePageFragment;
import com.auto.learning.fragment.MenuFragment;
import com.auto.learning.fragment.MenuFragment.SLMenuListOnItemClickListener;
import com.auto.learning.fragment.VideoPageFragment;
import com.auto.learning.net.Cache;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.DownLoadService2;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.service.PlayService;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CheckUpdateThread;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.CustomViewPager;
import com.auto.learning.view.RoundImageView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.auto.learning.view.SlidingTabLayout;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.CanvasTransformer;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenedListener;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class MainActivity extends SlidingFragmentActivity implements SLMenuListOnItemClickListener{
	
	private DownloadManager downloadManager;
	private SharedPreferences prefs;
	private static final String DL_ID = "downloadId";

	private SlidingTabLayout main_sliding_tabs;
	private CustomViewPager viewPager;
	private ImageView main_image_play,image_tips,image_tips_down;
	ArrayList<Fragment> fragmentArrayList = new ArrayList<Fragment>();
	private String mTabTitle[] = new String[]{"首页","选书","藏书","大咖秀"};
	private HomePageFragment homePageFragment;
	private VideoPageFragment videoPageFragment;
	private ChooseBookPageFragment chooseBookPageFragment;
	private CollectPageFragment collectFragment;
	private MenuFragment menuFragment;
	private RoundImageView main_image_me;
	
	private SlidingMenu mSlidingMenu;
	private LinearLayout main_top;
	
	private MyReceiver myReceiver;
	DisplayImageOptions options;
	private View v_redpoint;
	private int gotoBookList = 0;
	private boolean isClickUserFace = false;
	
	private Handle handler = new Handle(this){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -123:
				ResponeResult responeResult = (ResponeResult) msg.obj;
				if (responeResult != null && !TextUtils.isEmpty(responeResult.getData())) {
					try {
						JSONObject jsonObject = new JSONObject(responeResult.getData());
						final String screenUrl = jsonObject.getString("screenUrl");
						if (!TextUtils.isEmpty(screenUrl)) {
							ImageLoader.getInstance().loadImage(screenUrl, new SimpleImageLoadingListener(){
								public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
									if (loadedImage != null) {
										SharedPreferencesUtils.setParam(MainActivity.this, "isNeedShowScreenBoot", true);
										SharedPreferencesUtils.setParam(MainActivity.this, "ScreenBootImageUrl", screenUrl);
									}
								};
							});
						}else{
							SharedPreferencesUtils.setParam(MainActivity.this, "isNeedShowScreenBoot", false);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			case HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS:
				final BookBean bean = (BookBean) msg.obj;
				final int type = msg.arg1;
				if (bean != null) {
					if (TemporaryVariable.downLoadedList.contains(bean.getBookId())) {
						handler.postDelayed(new Runnable() {
							public void run() {
								ArrayList<BookBean> m_list = new ArrayList<BookBean>();
								m_list.add(bean);
								MusicPlayManager.getInstance(MainActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).setContinuePlayPause(type == 0 ? true : false).play();
							}
						}, 1500);
						Intent intent = new Intent(MainActivity.this, PlayActivity.class);
						intent.putExtra("bookId", bean.getBookId());
						intent.putExtra("needBuy", bean.getNeedBuy());
						intent.putExtra("canRead", bean.getCanRead());
						intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
						startActivity(intent);
				    }else{
						switch (CommonMethod.getNetworkState(MainActivity.this)) {
						case 0:
							CommonMethod.makeNotice(MainActivity.this, getResources().getString(R.string.connect_err_io));
							break;
						case 1:
							if(type == 0){
								Intent mIntent = new Intent(MainActivity.this, PlayActivity.class);
								mIntent.putExtra("bookId", bean.getBookId());
								mIntent.putExtra("canRead", bean.getCanRead());
								mIntent.putExtra("needBuy",bean.getNeedBuy());
								mIntent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
								mIntent.putExtra("break_point_continue", 1);   //这个值要是为1时就是点击右上角的icon进来且是还没有播放时候的，为0则为其他
								startActivity(mIntent);
							}else{
								handler.postDelayed(new Runnable() {
									public void run() {
										ArrayList<BookBean> m_list = new ArrayList<BookBean>();
										m_list.add(bean);
										MusicPlayManager.getInstance(MainActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).setContinuePlayPause(type == 0 ? true : false).play();
									}
								}, 1200);
								Intent intent = new Intent(MainActivity.this, PlayActivity.class);
								intent.putExtra("canRead", bean.getCanRead());
								intent.putExtra("needBuy",bean.getNeedBuy());
								intent.putExtra("bookId", bean.getBookId());
								intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
								startActivity(intent);
							}
							break;
						case 2:
							if(!(boolean)SharedPreferencesUtils.getParam(MainActivity.this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)){
								if(type == 0){
									Intent mIntent = new Intent(MainActivity.this, PlayActivity.class);
									mIntent.putExtra("bookId", bean.getBookId());
									mIntent.putExtra("canRead", bean.getCanRead());
									mIntent.putExtra("needBuy",bean.getNeedBuy());
									mIntent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
									mIntent.putExtra("break_point_continue", 1);   //这个值要是为1时就是点击右上角的icon进来且是还没有播放时候的，为0则为其他
									startActivity(mIntent);
								} else {
									CommonAlertDialog alertDialog = new CommonAlertDialog(MainActivity.this);
									String alertMsg = "";
									int size = bean.getProSize() + bean.getEnSize() + bean.getDoubiSize();
									if (size > 0) {
										alertMsg = String.format(getResources().getString(R.string.play_size_notice), CommonMethod.calculationNum(size));
									}
									alertDialog.setTextMessage(alertMsg+"");
									alertDialog.setShowTitle(true);
									String[] a = {"继续","取消"};
									alertDialog.setBtns(new DialogListener() {
										@Override
										public void okButtonClick(Dialog dialog) {
											dialog.dismiss();
											handler.postDelayed(new Runnable() {
												public void run() {
													ArrayList<BookBean> m_list = new ArrayList<BookBean>();
													m_list.add(bean);
													MusicPlayManager.getInstance(MainActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).setContinuePlayPause(type == 0 ? true : false).play();
												}
											}, 1500);
											Intent intent = new Intent(MainActivity.this, PlayActivity.class);
											intent.putExtra("bookId", bean.getBookId());
											intent.putExtra("canRead", bean.getCanRead());
											intent.putExtra("needBuy",bean.getNeedBuy());
											intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
											startActivity(intent);
										}
		
										@Override
										public void cancelButtonClick(Dialog dialog) {
											dialog.dismiss();
										}
		
										@Override
										public void otherButtonClick(Dialog dialog) {
											dialog.dismiss();
										}}, a);
									alertDialog.show();
								}
							}else{
								handler.postDelayed(new Runnable() {
									public void run() {
										ArrayList<BookBean> m_list = new ArrayList<BookBean>();
										m_list.add(bean);
										MusicPlayManager.getInstance(MainActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).setContinuePlayPause(type == 0 ? true : false).play();
									}
								}, 1500);
								Intent mIntent = new Intent(MainActivity.this, PlayActivity.class);
								mIntent.putExtra("bookId", bean.getBookId());
								mIntent.putExtra("canRead", bean.getCanRead());
								mIntent.putExtra("needBuy",bean.getNeedBuy());
								mIntent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
								startActivity(mIntent);
							}
							break;
						}
				    }
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				ResponeResult login_result = (ResponeResult) msg.obj;
				UserInfoBean userInfoBean = new Gson().fromJson(login_result.getData(), new TypeToken<UserInfoBean>(){}.getType());
				if (userInfoBean != null) {
					SharedPreferencesUtils.setParam(MainActivity.this, HttpRequestHelper.USERID, userInfoBean.getUserId());
					Cache.cacheUserInfo2Local(userInfoBean);
					//登录后刷新对应账号数据
					MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					menuFragment.refreshUi();
					menuFragment.getUserBaseInfo();
					loginSueecss();
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(MainActivity.this, msg.obj.toString());
				break;
			case 1:
				loginByUserName();
				break;
			case 11:
			case 12:
				ResponeResult m_result = (ResponeResult) msg.obj;
				try {
					if (m_result != null) {
						JSONObject jsonObject = new JSONObject(m_result.getData());
						int isChange = jsonObject.getInt(HttpRequestHelper.BOOKNUM_ISCHANGED);  //1否2是
						int bookNum = jsonObject.getInt("bookNum");
						int userId = (int) SharedPreferencesUtils.getParam(MainActivity.this, HttpRequestHelper.USERID, 0);
						if (isChange == 2) {
							SharedPreferencesUtils.setParam(MainActivity.this,  userId + "_" + HttpRequestHelper.BOOKNUM_ISCHANGED, isChange);
							EventBus.getEventBus("readbook_num_change").post(new BookNumChangeEvent(bookNum, msg.arg1));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		};
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.fg_main);
		initIntent();
		initImageLoader();
		initFragment();
		initView();
		registerEvent();
		registerReceiver();
		startService();
		TemporaryVariable.activities.push(this);
		CommonMethod.setAliasAndTags(this, 0);
		/**
		 * 同步收听记录到服务器
		 */
		uploadListenRecord();
	}
	
	String JPush_Data ;
	private void initIntent(){
		JPush_Data = getIntent().getStringExtra("JPush_Data");
	}
	
	
	private void startService(){
		Intent intent = new Intent(MainActivity.this, PlayService.class);
		startService(intent);
		Intent download_intent = new Intent(MainActivity.this, DownLoadService2.class);
		startService(download_intent);
	}
	
	
	
	
	public void showRefreshTips(){
		boolean hasShowDownLoad = (boolean) SharedPreferencesUtils.getParam(this, HttpRequestHelper.M_HAS_SHOW_HOME_REFRESH_DOWN, false);
		if (!hasShowDownLoad) {
			image_tips_down.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.tips_refresh_down));
			image_tips_down.setVisibility(View.VISIBLE);
		}
	}
	
	public void showRedTip(boolean isShow){
		if (v_redpoint != null) {
			v_redpoint.setVisibility(isShow ? View.VISIBLE : View.GONE);
		}
	}
	
	protected void initView() {
		gotoBookList = getIntent().getIntExtra("gotoBookList", 0);
		v_redpoint = findViewById(R.id.v_redpoint);
		image_tips = (ImageView) findViewById(R.id.image_tips);
		image_tips_down = (ImageView) findViewById(R.id.image_tips_down);
		main_top = (LinearLayout) findViewById(R.id.main_top); 
		main_top.setBackgroundColor(getResources().getColor(R.color.black));
		boolean hasShow = (boolean) SharedPreferencesUtils.getParam(this, HttpRequestHelper.M_HAS_SHOW_HOME_RIGHT, false);
		if (!hasShow && (int) SharedPreferencesUtils.getParam(this,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0) > 0) {
			image_tips.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.tips_home_right));
			image_tips.setVisibility(View.VISIBLE);
		}
		SharedPreferencesUtils.setParam(this, HttpRequestHelper.M_TILE_OFF, false);
		CommonMethod.cancelAlarm(this);
		downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(this); 
        try {
        	 if (prefs.contains(DL_ID)) {
             	downloadManager.remove(prefs.getLong(DL_ID, 0));
                prefs.edit().clear().commit(); 
     		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		setBehindContentView(R.layout.frame_left_menu);
		mSlidingMenu = getSlidingMenu();
		mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		mSlidingMenu.setFadeEnabled(false);
		mSlidingMenu.setBehindScrollScale(0.25f);
		mSlidingMenu.setFadeDegree(0.25f);
		mSlidingMenu.setBackgroundResource(R.drawable.mebg);
		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		mSlidingMenu.setBehindCanvasTransformer(new CanvasTransformer() {
				@Override
				public void transformCanvas(Canvas canvas, float percentOpen) {
					float scale = (float) (percentOpen * 0.25 + 0.75);
					canvas.scale(scale, scale, -canvas.getWidth() / 2, canvas.getHeight() / 2);
			}
		});

		mSlidingMenu.setAboveCanvasTransformer(new CanvasTransformer() {
				
			@Override
			public void transformCanvas(Canvas canvas, float percentOpen) {
				float scale = (float) (1 - percentOpen * 0.25);
				canvas.scale(scale, scale, 0, canvas.getHeight() / 2);
			}
		});
		mSlidingMenu.setOnOpenedListener(new OnOpenedListener() {
			
			@Override
			public void onOpened() {
				if (!isClickUserFace) {
					StatService.onEvent(MainActivity.this, "LogEventTypeHomePageSliceFromL", "首页左侧划-打开用户信息页面");
				}
				isClickUserFace = false;
			}
		});
		mSlidingMenu.setOnClosedListener(new OnClosedListener() {
			
			@Override
			public void onClosed() {
				homePageFragment.startTurning();
			}
		});
		

		// 设置 SlidingMenu 内容
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.replace(R.id.left_menu, menuFragment);
		fragmentTransaction.commit();
		
		
		main_image_play = (ImageView) findViewById(R.id.main_image_play);
		main_image_play.setBackgroundResource(R.drawable.now2);
		
		TabViewPagerAdapter adapter = new TabViewPagerAdapter(getSupportFragmentManager(), this, fragmentArrayList, mTabTitle);
		viewPager = (CustomViewPager) findViewById(R.id.viewpager);
		viewPager.setOffscreenPageLimit(mTabTitle.length);
	    viewPager.setAdapter(adapter);
	    
	    
	    main_sliding_tabs = (SlidingTabLayout) findViewById(R.id.main_sliding_tabs);
	    main_sliding_tabs.setCustomTabView(R.layout.tab_text, R.id.tv_tab_content,R.color.main_green_color,R.color.main_grake_color);
	    main_sliding_tabs.setDistributeEvenly(true);
	    main_sliding_tabs.setViewPager(viewPager);
	    main_sliding_tabs.setSelectedIndicatorColors(getResources().getColor(R.color.black));
	    main_sliding_tabs.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
					break;
				}
				chooseBookPageFragment.complateDrag();
				if (position == 1) {
					StatService.onEvent(MainActivity.this, "LogEventTypeOptionalVCAppearen", "选书页面打开");
				}else if(position == 2){
					StatService.onEvent(MainActivity.this, "LogEventTypeCollectionVCAppear", "藏书页面打开");
				}else if (position == 3) {
					StatService.onEvent(MainActivity.this, "LogEventTypeFameVCAppearence", "大咖秀页面打开");
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	    main_sliding_tabs.setBackgroundColor(getResources().getColor(R.color.black));
	    main_image_me = (RoundImageView) findViewById(R.id.main_image_me);
	    main_image_me.setType(RoundImageView.TYPE_CIRCLE);
	    main_image_me.setBorderRadius(0);
	    main_image_me.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			    isClickUserFace = true;
				StatService.onEvent(MainActivity.this, "LogEventTypeUserProfileButton", "用户信息按钮");
				menuFragment.getUserBaseInfo();
				toggle();
			}
		});
	    
	    main_image_play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				StatService.onEvent(MainActivity.this, "LogEventTypePlayViewButtonClic", "右上角的显示播放页面按钮");
				MusicPlayManager manager = MusicPlayManager.getInstance(MainActivity.this);
				if (manager.getPlayList() != null && manager.getPlayList().size() > 0) {
					Intent intent = new Intent(MainActivity.this, PlayActivity.class);
					intent.putExtra("bookId", manager.isPlayingBookId()[0]);
					intent.putExtra("faceImg", manager.getFaceImage());
					intent.putExtra("canRead", manager.getCanRead());
					int needBuy=1;
					//传递是否免费书籍判断
					for (int i = 0; i < manager.getPlayList().size(); i++) {
							if(manager.isPlayingBookId()[0]==manager.getPlayList().get(i).getBookId()){
								needBuy=manager.getPlayList().get(i).getNeedBuy();
							}
					}
					intent.putExtra("needBuy", needBuy);
					startActivity(intent);
				} else {
					boolean con = (boolean) SharedPreferencesUtils.getParam(MainActivity.this,HttpRequestHelper.CONTINUE_PLAY_BEFORE, true);
					if (con) {
						int bId = (int) SharedPreferencesUtils.getParam(MainActivity.this,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
						if (bId != 0) {
							Cache.getBookBeanById(MainActivity.this,bId, handler, 0);
						}
					}
				}
			}
		});
	    image_tips.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				image_tips.setVisibility(View.GONE);
				SharedPreferencesUtils.setParam(MainActivity.this, HttpRequestHelper.M_HAS_SHOW_HOME_RIGHT, true);
			}
		});
	    image_tips_down.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				image_tips_down.setVisibility(View.GONE);
				SharedPreferencesUtils.setParam(MainActivity.this, HttpRequestHelper.M_HAS_SHOW_HOME_REFRESH_DOWN, true);
			}
		});
	    HttpRequestHelper.getScreenImage(MainActivity.this, handler);
	    new CheckUpdateThread(this,1).execute();
	    if (gotoBookList > 0) {
	    	Intent intent = new Intent(this, BookListActivity.class);
	    	BookListModel bookListModel = new BookListModel();
	    	bookListModel.setListId(gotoBookList);
			intent.putExtra("data", bookListModel);
			startActivity(intent);
		} else if (!TextUtils.isEmpty(JPush_Data)) {
			try {
				Intent mIntent = null;
				JSONObject jsonObject = new JSONObject(JPush_Data);
				String web_h5 = jsonObject.optString("h5", "");
				if (!TextUtils.isEmpty(web_h5)) {
					Banner_H5 banner_H5 = new Gson().fromJson(web_h5, new TypeToken<Banner_H5>() {}.getType());
					if (banner_H5 != null) {
						mIntent = new Intent(MainActivity.this, WebActivity.class);
						mIntent.putExtra("url", banner_H5.getH5().replace("{userId}", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, HttpRequestHelper.USERID, 0))));
						mIntent.putExtra("showtitle", true);
						mIntent.putExtra("title",banner_H5.getName()+"");
						mIntent.putExtra("h5_model", banner_H5);
						startActivity(mIntent);
					}
				} else {
					int JPush_type = jsonObject.optInt("type", 0);
					switch (JPush_type) {
					case 1:
						mIntent = new Intent(this, MyMessageActivity.class);
						mIntent.putExtra("msg_type", 1);
						startActivityForResult(mIntent, 130);
						break;
					case 2:
						int bookId = jsonObject.getInt("id");
						String faceImg = jsonObject.getString("faceImg");
						int canRead=jsonObject.getInt("canRead");
						int needBuy=jsonObject.getInt("needBuy");
						TemporaryVariable.read_list.clear();
						TemporaryVariable.read_list.add(bookId);
						if (TemporaryVariable.playActivity != null && TemporaryVariable.playActivity instanceof PlayActivity) {
							TemporaryVariable.playActivity.finish();
						}
						mIntent = new Intent(this, PlayActivity.class);
						mIntent.putExtra("bookId", bookId);
						mIntent.putExtra("faceImg", faceImg);
						mIntent.putExtra("canRead",canRead);
						mIntent.putExtra("needBuy",needBuy);
						mIntent.putExtra("type", 1);
						startActivity(mIntent);
						break;
					case 3:
						int listId = jsonObject.getInt("id");
						mIntent = new Intent(this, BookListActivity.class);
				    	BookListModel bookListModel = new BookListModel();
				    	bookListModel.setListId(listId);
				    	mIntent.putExtra("data", bookListModel);
						startActivity(mIntent);
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void setCanScroll(boolean can){
		if (viewPager != null) {
			viewPager.setScanScroll(can);
		}
	}
	
	
	public void playContunie(){
		int bId = (int) SharedPreferencesUtils.getParam(MainActivity.this,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
		if (bId != 0) {
			Cache.getBookBeanById(MainActivity.this,bId, handler, 1);
		}
	}
	
	public void showMainActivity(){
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				showContent();
				homePageFragment.startTurning();
			}
		}, 1000);
	}
	
	public void gotoHome(){
		if (viewPager != null) {
			viewPager.setCurrentItem(0);
		}
	}
	
	
	@Override
	protected void onDestroy() {
		CommonMethod.recordBreakPoint();
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		if (myReceiver != null) {
			unregisterReceiver(myReceiver);
		}
		stopService(new Intent(MainActivity.this, PlayService.class));
		stopService(new Intent(MainActivity.this, DownLoadService2.class));
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
//		Log.d("onEventPlayStute", isPlaying+"");
		MusicPlayManager manager = MusicPlayManager.getInstance(this);
		manager.setPlaying(isPlaying);
//		manager.setShowNetTips(true);
		if (isPlaying && HttpCommonInfo.M_NET_DIALOG_SHOW) {
			EventBus.getEventBus("m_pause").post(false);
		}
		if (isPlaying && manager.needCheckNet()) {
			manager.setShowNetTips(false);
			if (isPlaying) {
				manager.pause();
			}
			CommonMethod.showMobileNetTips(TemporaryVariable.getTopActivity(), new DialogListener() {
				
				@Override
				public void otherButtonClick(Dialog dialog) {
					dialog.dismiss();
					HttpCommonInfo.M_NET_DIALOG_SHOW = false;
					MusicPlayManager.getInstance(MainActivity.this).setShowNetTips(true);
				}
				
				@Override
				public void okButtonClick(Dialog dialog) {
					dialog.dismiss();
					HttpCommonInfo.M_NET_DIALOG_SHOW = false;
					MusicPlayManager.getInstance(MainActivity.this).setShowNetTips(false);
					MusicPlayManager.getInstance(MainActivity.this).pause();
				}
				
				@Override
				public void cancelButtonClick(Dialog dialog) {
					dialog.dismiss();
					MusicPlayManager.getInstance(MainActivity.this).setShowNetTips(true);
					HttpCommonInfo.M_NET_DIALOG_SHOW = false;
				}
			});
		}
		homePageFragment.hideTip();
		if (isPlaying) {
			main_image_play.setBackgroundResource(R.anim.play_stute);
			AnimationDrawable _animaition = (AnimationDrawable)main_image_play.getBackground();
			_animaition.setOneShot(false);   
			_animaition.start();
		} else {
			main_image_play.setBackgroundResource(R.drawable.now2);
		}
		homePageFragment.notifyUI();
//		chooseBookPageFragment.notifyUI();
		collectFragment.notifyUI();
	}
	
	@Subscribe
	public void onEventPlayNext(Integer next){
		MusicPlayManager.getInstance(this).next();
	}
	
	@Subscribe
	public void onEventUpdateApk(VersionInfo versionInfo){
//		new DownLoadAppThread(this, versionInfo).start();
		downloadApk(versionInfo.getApkUrl());
	}
	
	@Subscribe
	public void onEventInstallApk(String path){
		updateApk(path);
	}

	public void addIgnoredView(View v) {
		mSlidingMenu.addIgnoredView(v);
	}
	/*@Subscribe
	public void onEventLunchLockScreen(LunchLockScreenEvent event){
		boolean mFlag = false;
		if (TemporaryVariable.activity != null) {
			TemporaryVariable.activity.finish();
			TemporaryVariable.activity = null;
			mFlag = true;
		}
		BookBean nowPLayBean = MusicPlayManager.getInstance(MainActivity.this).getCurrentPlayingBookBean();
		if (nowPLayBean != null) {
			Intent intent = new Intent(MainActivity.this, SrceenLockActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("lock_bookbean_info", nowPLayBean);
			intent.putExtra("isBackGround", mFlag ? false :CommonMethod.isBackground(MainActivity.this));
			startActivity(intent);
		}
	}*/
	
	@Subscribe
	public void onEventBookNumChanged(BookNumChangeEvent event){
		int num = event.getBookNum();
		MyUserInfo.getInstance().getUserInfoBean().setBookNum(num);
		menuFragment.refreshUserReadBookNumber(num);
		homePageFragment.refreshNewAndTopBook(event.getBookId());
//		chooseBookPageFragment.refreshListWhenBookNumChanged(event.getBookId());
//		collectFragment.refreshWhenBookNumChanged(event.getBookId());
	}
	
	@Subscribe
	public void onEventBindSuccessed(BindSuccessEvent event){
		int type = event.getRefreshType();
		if (type == 206) {
			loginByUserName();
		}else if (type == 207){
			menuFragment.refreshUi();
			menuFragment.getUserBaseInfo();
		}
	}
	
	/**
	 * 登录成功后设置别名和Tag
	 * @param userInfoBean
	 */
	@Subscribe
	public void onEventLoginSuccessJPushSetAliseAndTags(UserInfoBean userInfoBean){
		if (userInfoBean != null) {
			CommonMethod.setAliasAndTags(this, userInfoBean.getUserId());
		}
	}
	
	/**
	 * 显示小红点
	 * @param userInfoBean
	 */
	@Subscribe
	public void onEventShowTipRed(MainShowTipEvent event){
		showRedTip(event.isShow());
	}
	
	public void uploadListenRecord(){
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				Pool.getPool().execute(new Runnable() {
					
					@Override
					public void run() {
						HttpRequestHelper.synchronousListenStatus(MainActivity.this, handler);
					}
				});				
			}
		}, 10 * 1000);
		
	}
	
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_play_next" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("update_apk", ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("install_apk", ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("login_success_refreshUI",ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("login_refreshUI",ThreadEnforcer.MAIN).register(this);
//		EventBus.getEventBus("lunch_lock_screen",ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("readbook_num_change",ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("bind_success_refresh",ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("login_success_alise_tag",ThreadEnforcer.MAIN).register(this);  //登录成功后设置别名
		EventBus.getEventBus("JPush_show_tip_red",ThreadEnforcer.MAIN).register(this);  //接收到通知之后设置小红点
	}
	
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_play_next" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("update_apk", ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("install_apk", ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("login_success_refreshUI",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("login_refreshUI",ThreadEnforcer.MAIN).unregister(this);
//		EventBus.getEventBus("lunch_lock_screen",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("readbook_num_change",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("bind_success_refresh",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("login_success_alise_tag",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("JPush_show_tip_red",ThreadEnforcer.MAIN).unregister(this);  //接收到通知之后设置小红点
	}
	
	@Subscribe
	public void onEventRefresh(ResponeResult data){
		handler.obtainMessage(HttpRequestHelper.PUBLIC_LOGIN_SUCCESS, data).sendToTarget();
	}
	
	@Subscribe
	public void onEventRefreshUI(LoginSuccessEvent event){
		handler.sendEmptyMessage(1);
	}
	
	/*
	 * @description 下载完成后自动安装apk
	 */
	private void updateApk(String filePath) {
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);
			if (null == file || !file.exists()) {
				return;
			}
			Uri uri = Uri.fromFile(file);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(uri, "application/vnd.android.package-archive");
			startActivity(intent);
		}
	}
	
	/**
	 * 注册广播
	 */
	public void registerReceiver(){
		myReceiver = new MyReceiver();
		IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
		filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		registerReceiver(myReceiver, filter);
	}
	
	class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {  //拔出耳机
				if (MusicPlayManager.getInstance(context).isPlaying()) {
					MusicPlayManager.getInstance(context).pause();
				}
			}else if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
				//这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
		    	Log.v("intent", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
		        queryDownloadStatus(); 
			}
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			exitDialog();
		}
		return false;
	}
	
	private void exitDialog(){
		CommonAlertDialog alertDialog = new CommonAlertDialog(this);
		alertDialog.setTextMessage("确认退出吗？");
		alertDialog.setShowTitle(true);
		String[] a = {"确定","后台播放","取消"};
		alertDialog.setBtns(new DialogListener() {

			@Override
			public void okButtonClick(Dialog dialog) {
				dialog.dismiss();
				CommonMethod.recordBreakPoint();
				//MainActivity.this.finish();
				try {
					stopService(new Intent(MainActivity.this,PlayService.class));
					stopService(new Intent(MainActivity.this, DownLoadService2.class));
				} catch (Exception e) {
					e.printStackTrace();
				}
				android.os.Process.killProcess(android.os.Process.myPid());
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				//moveTaskToBack(true);
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);           
				startActivity(intent);
				dialog.dismiss();
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				dialog.dismiss();
			}}, a);
		alertDialog.show();
	}
	
	
	
	private void initFragment(){
		menuFragment = new MenuFragment();
		homePageFragment = new HomePageFragment();
		ArrayList<BookBean> m_bookList = new ArrayList<BookBean>();
		ArrayList<BookBean> m_newList = new ArrayList<BookBean>();
		ArrayList<BookBean> m_topList = new ArrayList<BookBean>();
		ArrayList<BannerItem> m_bannerList = new ArrayList<BannerItem>();
		m_bookList.addAll(HttpRequestHelper.bookList);
		m_newList.addAll(HttpRequestHelper.newList);
		m_topList.addAll(HttpRequestHelper.topList);
		m_bannerList.addAll(HttpRequestHelper.bannerItemList);
		homePageFragment.setList(m_bannerList);
		homePageFragment.setBookList(m_bookList);
		homePageFragment.setNewList(m_newList);
		homePageFragment.setTopList(m_topList);
		HttpRequestHelper.bookList.clear();
		HttpRequestHelper.bannerItemList.clear();
		HttpRequestHelper.newList.clear();
		HttpRequestHelper.topList.clear();
		videoPageFragment = new VideoPageFragment();
		chooseBookPageFragment = new ChooseBookPageFragment();
		collectFragment = new CollectPageFragment();
		fragmentArrayList.add(homePageFragment);
		fragmentArrayList.add(chooseBookPageFragment);
		fragmentArrayList.add(collectFragment);
		fragmentArrayList.add(videoPageFragment);
	}

	@Override
	public void selectItem(int position, String title) {
		
	}
	
	public void loginSueecss(){
		homePageFragment.loginSuccess();
//		collectFragment.loginSuccess();
		chooseBookPageFragment.refreshUI();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(MainActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handler);
				}
			});
		} else if (requestCode == 100 && (resultCode == 204 || resultCode == 206)) {
			loginByUserName();
		} else if ((requestCode == 101 && resultCode == 205) || (requestCode == 100 && resultCode == 205) || (requestCode == 100 && resultCode == 207)) {
			menuFragment.refreshUi();
			menuFragment.getUserBaseInfo();
		} else if (requestCode == 130) {
			menuFragment.refreshUi();
		}else if (requestCode == 660 && resultCode == 661) {
			gotoHome();
			collectFragment.getDownLoadList();
		}else if (requestCode == 660 && resultCode == 662) {
			collectFragment.getDownLoadList();
		}else if (requestCode == 559 && resultCode == 560) {  //订阅成功后
			menuFragment.openUserBaseInfo();
			menuFragment.refreshUi();
		}
	}
	
	@Override
	protected void onPause() {
		CommonMethod.recordBreakPoint();
		super.onPause();
	}
	
	
	
	private void loginByUserName(){
		menuFragment.refreshUi();
		menuFragment.getUserBaseInfo();
		loginSueecss();
	}
	
	public void refreshHead(String faceUrl){
		if (TextUtils.isEmpty(faceUrl)) {
			main_image_me.setImageResource(R.drawable.me);
		}else {
			ImageLoader.getInstance().displayImage(faceUrl, main_image_me, options);
		}
	}
	
	public int getCurrentPage(){
		int position = -1;
		if (viewPager != null) {
			position = viewPager.getCurrentItem();
		}
		return position;
	}
	
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me)
		.showImageForEmptyUri(R.drawable.me)
		.showImageOnFail(R.drawable.me).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
	private void downloadApk(String url){
		File file = new File(FileUtil.getFileCachePath() + "/" + DownLoadInfo.APK_CACHE_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}else {
			File m_file = new File(FileUtil.getFileCachePath() + "/" + DownLoadInfo.APK_CACHE_PATH +"/AutoLearning.apk");
			if (m_file.exists()) {
				m_file.delete();
			}
		}
		try {
			downloadManager.remove(prefs.getLong(DL_ID, 0));
	        prefs.edit().clear().commit(); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(!prefs.contains(DL_ID)) { 
	        //开始下载 
	        Uri resource = Uri.parse(encodeGB(url)); 
	        DownloadManager.Request request = new DownloadManager.Request(resource); 
	        request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI); 
	        request.setAllowedOverRoaming(true); 
	        //设置文件类型
	        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
	        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
	        request.setMimeType(mimeString);
	        
	        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
	        //在通知栏中显示 
	        request.setShowRunningNotification(true);
	        request.setVisibleInDownloadsUi(true);
	        //sdcard的目录下的文件夹
//	        request.setDestinationInExternalPublicDir("/android/data/com.auto.learning/cache/"+ DownLoadInfo.APK_CACHE_PATH, "AutoLearning.apk");
	        request.setDestinationInExternalPublicDir(DownLoadInfo.MAIN_ROOT +"/" + DownLoadInfo.APK_CACHE_PATH, "AutoLearning.apk");
	        request.setTitle("路上读书更新"); 
	        long id = downloadManager.enqueue(request); 
	        //保存id 
	        prefs.edit().putLong(DL_ID, id).commit(); 
	    } else { 
	        //下载已经开始，检查状态
	        queryDownloadStatus(); 
	    } 
	}
	
	
	/**
	 * 如果服务器不支持中文路径的情况下需要转换url的编码。
	 * @param string
	 * @return
	 */
	public String encodeGB(String string)
	{
		//转换中文编码
		String split[] = string.split("/");
		for (int i = 1; i < split.length; i++) {
			try {
				split[i] = URLEncoder.encode(split[i], "GB2312");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			split[0] = split[0]+"/"+split[i];
		}
		split[0] = split[0].replaceAll("\\+", "%20");//处理空格
		return split[0];
	}
	
	private void queryDownloadStatus() { 
	    DownloadManager.Query query = new DownloadManager.Query(); 
	    query.setFilterById(prefs.getLong(DL_ID, 0)); 
	    Cursor c = downloadManager.query(query); 
	    if(c.moveToFirst()) { 
	        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); 
	        switch(status) { 
	        case DownloadManager.STATUS_PAUSED: 
	        	Log.v("down", "STATUS_PAUSED");
	        case DownloadManager.STATUS_PENDING: 
	        	Log.v("down", "STATUS_PENDING");
	        case DownloadManager.STATUS_RUNNING: 
	            //正在下载，不做任何事情
	        	Log.v("down", "STATUS_RUNNING");
	            break; 
	        case DownloadManager.STATUS_SUCCESSFUL: 
	            //完成
	        	prefs.edit().clear().commit(); 
	        	updateApk(FileUtil.getFileCachePath() +"/"+ DownLoadInfo.APK_CACHE_PATH +"/AutoLearning.apk");
	        	break; 
	        case DownloadManager.STATUS_FAILED: 
	            //清除已下载的内容，重新下载
	        	Log.v("down", "STATUS_FAILED");
	        	downloadManager.remove(prefs.getLong(DL_ID, 0)); 
	            prefs.edit().clear().commit(); 
	            break; 
	        } 
	    }
	}
	
	
}
